package com.yuhao.init.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuhao.init.common.BaseResponse;
import com.yuhao.init.common.ErrorCode;
import com.yuhao.init.common.ResultUtils;
import com.yuhao.init.config.MinioConfig;
import com.yuhao.init.constant.FileConstant;
import com.yuhao.init.exception.BusinessException;
import com.yuhao.init.mapper.BannerMapper;
import com.yuhao.init.model.dto.banner.RequestBanner;
import com.yuhao.init.model.entity.Banner;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Resource;

import com.yuhao.init.model.vo.PageResultVo;
import com.yuhao.init.utils.MinioUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件接口
 *
 * @author
 * @from
 */
@RestController
@RequestMapping("/banner")
@Slf4j
public class BannerController {


    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private MinioConfig minioConfig;

    @Resource
    private BannerMapper bannerMapper;

    /**
     * 文件上传
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse uploadFile(@RequestPart("file") MultipartFile multipartFile) throws IOException {
        //校验图片是否符合规范
        Boolean validFile = validFile(multipartFile);
        if (!validFile)return ResultUtils.error(ErrorCode.OPERATION_ERROR,"文件不符合要求");
        String objectName = minioUtil.upload(multipartFile,"banner");
        if (null == objectName) {
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, "上传失败");
        }
        String picurl = FileConstant.COS_HOST + "/" + minioConfig.getBucketName() + "/" + objectName;
        log.info("上传成功，url为:{}", picurl);
        return ResultUtils.success(picurl,"上传成功");
    }
    @PostMapping("/add")
    public BaseResponse addBanner(@RequestBody RequestBanner requestBanner) {

        if (requestBanner==null || requestBanner.getPicurl()==null){
            return ResultUtils.error(ErrorCode.PARAMS_ERROR,"数据为空");
        }
        if ( StringUtils.isBlank(requestBanner.getPicurl())){
            return ResultUtils.error(ErrorCode.PARAMS_ERROR,"图片不能为空");
        }
        Banner banner = new Banner();
        banner.setPicurl(requestBanner.getPicurl());
        banner.setSort(requestBanner.getSort());
        banner.setTarget(requestBanner.getTarget());
        banner.setUrl(requestBanner.getUrl());
        int insert = bannerMapper.insert(banner);
        return ResultUtils.success(null,insert>0 ? "添加成功" : "添加失败");
    }

    @GetMapping("/list")
    public BaseResponse<PageResultVo<Banner>> listBanner(Long pageSize , Long currentPage) {
        if (pageSize == null || currentPage == null || pageSize.intValue()<0 || currentPage.intValue()<0) {
            pageSize = 10L;
            currentPage = 1L;
        }
        Long total = bannerMapper.selectCount(null);
        Page<Banner> page = bannerMapper.selectPage(new Page<>(currentPage, pageSize),null);
        List<Banner> records = page.getRecords();
        return ResultUtils.success(new PageResultVo<>(total,records));
    }

    @GetMapping("/get")
    public BaseResponse getBannerById(int id) {
        if (id==0){
            return ResultUtils.error(ErrorCode.PARAMS_ERROR,"请求参数错误");
        }
        Banner banner = bannerMapper.selectById(id);
        return ResultUtils.success(banner);
    }

    @PostMapping("/edit")
    public BaseResponse getBannerById(@RequestBody Banner banner) {
        if (banner==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数错误");
        }
        int status = bannerMapper.updateById(banner);
        System.out.println("status"+status);
      return  ResultUtils.success(null,"更新成功");
    }


    @DeleteMapping("/delete")
    public BaseResponse deleteBanner(Long id){
        if (id==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数错误");
        }
        int i = bannerMapper.deleteById(id);
        return ResultUtils.success(null,i>0? "删除成功" :"删除失败");
    }

    /**
     * 校验文件
     * @param multipartFile
     */
    private Boolean validFile(MultipartFile multipartFile) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        System.out.println("文件尺寸:" + fileSize);
        if (fileSize > 3 * 1024 * 1024L) {
            return false;
        }
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        return Arrays.asList("jpg", "png", "jpeg").contains(fileSuffix);
    }
}
